//
//  SEGCommonDoorConfigViewController.m
//  SEGIntelligentHardware
//
//  Created by Clavis on 2019/5/5.
//  Copyright © 2019 Clavis. All rights reserved.
//

#import "SEGCommonDoorConfigViewController.h"
#import "SEGCommonDoorConfigCollectionViewCell.h"
#import "SEGNewMyDoorListModel.h"
//ViewModel
#import <SEGViewModel/SEGDoorListViewModel.h>
#import <ReactiveObjC/ReactiveObjC.h>

@interface SEGCommonDoorConfigViewController () <UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView *commonDoorCollectionView;
@property (nonatomic, strong) UICollectionView *allDoorCollectionView;
@property (nonatomic, strong) NSArray<SEGNewMyDoorListModel *> *allDoorList;
@property (nonatomic, strong) NSArray<SEGNewMyDoorListModel *> *commonDoorList;
@property (nonatomic, strong) SEGDoorListViewModel *doorListViewModel;

@end

@implementation SEGCommonDoorConfigViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    
    @weakify(self);
    [SVProgressHUD show];
    [[self.doorListViewModel requestNetAllDoorList] subscribeNext:^(NSArray<SEGNewMyDoorListModel *> * _Nullable doorList) {
        @strongify(self);
        [SVProgressHUD dismiss];
        self.allDoorList = [doorList copy];
        self.commonDoorList = [self.doorListViewModel getOldCommonDoor];
        [self.commonDoorCollectionView reloadData];
        [self.allDoorCollectionView reloadData];
        if (self.allDoorList.count == 0) {
            [[SEGUhomeMediator sharedInstance] seg_showCustomProgressImage:@{@"view":self.view,@"text":@"这儿什么门都没有",@"backcolor":kColor_W}];
        }
    }];
}

- (void)setupUI {
    self.title = @"设置常用门";
    self.view.backgroundColor = kColor_W;
    [self showCustomNavigationBackButton];
    [self setAutomaticallyAdjustsScrollViewInsets:NO];
    if ([self respondsToSelector:@selector(setAutomaticallyAdjustsScrollViewInsets:)]) {
        self.automaticallyAdjustsScrollViewInsets = NO;//禁用掉自动设置的内边距，自行控制controller上index为0的控件以及scrollview控件的位置
    }
    
    UILabel *tipLabel = ({
        UILabel *label = [[UILabel alloc] init];
        [self.view addSubview:label];
        NSMutableAttributedString *tipString = [[NSMutableAttributedString alloc] initWithString:@"常用门" attributes:@{NSForegroundColorAttributeName : kColor_1, NSFontAttributeName: kFont_15}];
        [tipString appendAttributedString:[[NSAttributedString alloc] initWithString:@"  (最多只能设置6个常用门）" attributes:@{NSForegroundColorAttributeName : kColor_3, NSFontAttributeName: kFont_15}]];
        label.attributedText = tipString;
        label;
    });
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.top.mas_equalTo(0);
        make.height.mas_equalTo(40);
    }];
    
    CGFloat collectionMargin = 13;
    CGFloat cellMargin = 9;
    CGFloat cellWith = (LYScreenWidth() - collectionMargin*2 - cellMargin)/2.0;
    CGFloat cellHeight = 44;
    self.commonDoorCollectionView = ({
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.minimumLineSpacing = cellMargin;
        layout.minimumInteritemSpacing = cellMargin;
        layout.itemSize = CGSizeMake(cellWith, cellHeight);
        UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        collectionView.collectionViewLayout = layout;
        collectionView.delegate = self;
        collectionView.dataSource = self;
        [collectionView registerClass:[SEGCommonDoorConfigCollectionViewCell class] forCellWithReuseIdentifier:@"configCell"];
        collectionView.backgroundColor = UIColor.clearColor;
        collectionView.contentInset = UIEdgeInsetsMake(0, collectionMargin, 0, collectionMargin);
        [self.view addSubview:collectionView];
        collectionView;
    });
    [self.commonDoorCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(tipLabel.mas_bottom);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo((cellHeight+cellMargin)*3);
    }];
    
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = kColor_bg;
    [self.view addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.commonDoorCollectionView.mas_bottom).offset(5);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(8);
    }];
    
    UILabel *allDoorTitle = ({
        UILabel *label = [[UILabel alloc] init];
        [self.view addSubview:label];
        label.textColor = kColor_1;
        label.font = kFont_15;
        label.text = @"所有大门";
        label;
    });
    [allDoorTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lineView.mas_bottom);
        make.left.mas_equalTo(collectionMargin);
        make.height.mas_equalTo(35);
    }];
    
    self.allDoorCollectionView = ({
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.minimumLineSpacing = cellMargin;
        layout.minimumInteritemSpacing = cellMargin;
        layout.itemSize = CGSizeMake(cellWith, cellHeight);
        UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        collectionView.collectionViewLayout = layout;
        collectionView.delegate = self;
        collectionView.dataSource = self;
        [collectionView registerClass:[SEGCommonDoorConfigCollectionViewCell class] forCellWithReuseIdentifier:@"configCell"];
        collectionView.backgroundColor = UIColor.clearColor;
        collectionView.contentInset = UIEdgeInsetsMake(0, collectionMargin, 15, collectionMargin);
        [self.view addSubview:collectionView];
        collectionView;
    });
    [self.allDoorCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(allDoorTitle.mas_bottom);
        make.left.right.bottom.mas_equalTo(0);
    }];
}

// 判断door是否已经被选择
- (BOOL)judgeDoorModelIsSelect:(SEGNewMyDoorListModel *)doorModel {
    BOOL __block flag = NO;
    [self.commonDoorList enumerateObjectsUsingBlock:^(SEGNewMyDoorListModel * _Nonnull commonDoor, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([doorModel.doorId isEqualToString:commonDoor.doorId]) {
            flag = YES;
            *stop = YES;
        }
    }];
    return flag;
}

#pragma mark - <UICollectionViewDelegate, UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return collectionView == self.commonDoorCollectionView ? 6 : self.allDoorList.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SEGCommonDoorConfigCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"configCell" forIndexPath:indexPath];
    
    if (collectionView == self.commonDoorCollectionView) {
        if (indexPath.row < self.commonDoorList.count) {
            SEGNewMyDoorListModel *commonDoor = self.commonDoorList[indexPath.row];
            [cell updateCellWithModel:commonDoor displayType:SEGCommonDoorConfigCellDisplayTypeCanDelete];
        } else {
            [cell updateCellWithModel:nil displayType:SEGCommonDoorConfigCellDisplayTypeNone];
        }
    } else {
        SEGNewMyDoorListModel *doorModel = self.allDoorList[indexPath.row];
        [cell updateCellWithModel:doorModel displayType:[self judgeDoorModelIsSelect:doorModel] ? SEGCommonDoorConfigCellDisplayTypeDidSelect : SEGCommonDoorConfigCellDisplayTypeCanAdd];
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.commonDoorCollectionView) {
        if (indexPath.row < self.commonDoorList.count) {
            NSMutableArray *tempCommonArray = [NSMutableArray arrayWithArray:self.commonDoorList];
            [tempCommonArray removeObjectAtIndex:indexPath.row];
            self.commonDoorList = [tempCommonArray copy];
        }
    } else {
        SEGNewMyDoorListModel *doorModel = self.allDoorList[indexPath.row];
        if (![self judgeDoorModelIsSelect:doorModel]) {
            if (self.commonDoorList.count == 6) {
                [SEGAlertView showTmepMessageWithMessage:@"亲，最多只能设置6个常用门哦"];
                return;
            }
            NSMutableArray *tempCommonArray = [NSMutableArray arrayWithArray:self.commonDoorList];
            [tempCommonArray addObject:doorModel];
            self.commonDoorList = [tempCommonArray copy];
        }
    }
    // 更新并缓存常用门
    [self.doorListViewModel updateOldCommonDoors:self.commonDoorList];
    [self.commonDoorCollectionView reloadData];
    [self.allDoorCollectionView reloadData];
}

#pragma mark - Getter
- (SEGDoorListViewModel *)doorListViewModel {
    if (!_doorListViewModel) {
        _doorListViewModel = [SEGDoorListViewModel new];
    }
    return _doorListViewModel;
}

@end
